package common

import (
	"time"

	"github.com/dgrijalva/jwt-go"
	"sweeter.star/go-demo/model"
)

var jwtKey = []byte("go.demo")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

/**
 * JWT 发布加密 TOKEN
 * @author sweeter 2022-01-07
 * @param token string
 * @return token, claims, error
 */
func ReleaseToken(user model.User) (string, error) {
	// TOKEN 有效期 7天
	expireTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), // 失效日期
			IssuedAt: time.Now().Unix(), // 发布日期
			Issuer: "sweeter.star", // 发布人
			Subject: "user token", // 主题
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)

	if err != nil {
		return "", err
	}

	return tokenString, nil
}

/**
 * JWT 解密 TOKEN
 * @author sweeter 2022-01-07
 * @param token string
 * @return token, claims, error
 */
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(
		tokenString,
		claims,
		func(token *jwt.Token) (i interface{}, err error) {
			return jwtKey, nil
		})

	return token, claims, err
}